<?php

namespace app\store\service\order;

use app\store\model\OrderAddress as OrderAddressModel;

/**
 * 订单导出服务类
 * Class Export
 * @package app\store\service\order
 */
class Export
{
    /**
     * 表格标题
     * @var array
     */
    private $tileArray = [
        '订单号', '挂号医生', '挂号费', '实付款', '推荐人', '就诊人',
        '就诊人电话', 
        '预约时间', '支付方式', '付款状态', '就诊状态'
    ];
    private $tileArray1 = [
        '订单号', '商品信息', '订单总额', '优惠券抵扣', '积分抵扣', '运费金额', '后台改价', '实付款金额', '支付方式', '下单时间',
        '买家', '买家留言', '配送方式', '自提门店名称', '自提联系人', '自提联系电话', '收货人姓名', '联系电话', '收货人地址',
        '物流公司', '物流单号', '付款状态', '付款时间', '发货状态', '发货时间', '收货状态', '收货时间', '订单状态', '微信支付交易号', '是否已评价'
    ];
    /**
     * 分销商导出
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function delist($headers,$data)
    {
        // 表格内容
        $dataArray = [];
        foreach ($data as $order) {
            $dataArray[] = [
                '微信昵称' => $order['nickName'],
                '姓名' => $order['jiuzhen_name'],
                '手机号' => $order['jiuzhen_phone'],
                '累计推荐人数' => $order['total_recommended'],
                '添加人' => '平台',
                '成为时间' => $order['create_time'],
                
            ];
        }
        // 导出csv文件
        $filename = 'dealer-' . date('YmdHis');
        return export_excel($filename . '.csv', $headers, $dataArray);
    }
    public function delist2($headers,$data)
    {
        // dump($headers);
        
        // 表格内容
        $dataArray = [];
        foreach ($data as $order) {
            // dump($order['nickName']);die;
            $dataArray[] = [
                '分销员' => $order['nickName'],
                '推荐人' => $order['jiuzhen_name'],
                '手机号' => $order['jiuzhen_phone'],
                '下级数量' => $order['total_recommended'],
                '成为时间' => $order['create_time'],
                
            ];
        }
        // 导出csv文件
        $filename = 'dealer-' . date('YmdHis');
        return export_excel($filename . '.csv', $headers, $dataArray);
    }
    public function delist1($headers, $data)
    {
        // 初始化表头数组，用于动态生成
        $dynamicHeaders = [];

        // 处理数据并生成动态表头
        $dataArray = [];
        foreach ($data as $order) {
            // 解码调研结果的 JSON 数据
            $decodedAnswerText = htmlspecialchars_decode($order['answer_text']); // 解码 HTML 转义字符
            $answerText = json_decode($decodedAnswerText, true);

            // 初始化当前行数据
            $rowData = [
                '问卷标题' => $order['survey_title'],
                '用户' => $order['jiuzhen_name'] ?? '--',
                '手机号' => $order['jiuzhen_phone'] ?? '--',
                '时间' => date("Y-m-d", $order['create_time']),
            ];

            // 动态解析调研结果
            if (json_last_error() === JSON_ERROR_NONE && is_array($answerText)) {
                foreach ($answerText as $key => $value) {
                    // 确保值为字符串或数组（避免复杂类型）
                    if (is_array($value)) {
                        $value = implode(',', $value); // 将数组值转换为逗号分隔的字符串
                    }
                    // 动态加入表头
                    if (!in_array($key, $dynamicHeaders)) {
                        $dynamicHeaders[] = $key;
                    }
                    // 设置行数据
                    $rowData[$key] = $value ?? '--';
                }
            } else {
                // JSON 解析失败时，将调研结果原样加入一个列
                $rowData['原始调研结果'] = $order['answer_text'] ?? '--';
            }

            $dataArray[] = $rowData;
        }

        // 最终表头 = 固定表头 + 动态表头
        $finalHeaders = array_merge($headers, $dynamicHeaders);

        // 导出 CSV 文件
        $filename = 'diaoyan-' . date('YmdHis');
        return export_excel($filename . '.csv', $finalHeaders, $dataArray);
    }
    /**
     * 订单导出
     * @param $list
     */
    public function orderList($list)
    {
        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            /* @var OrderAddressModel $address */
            // '订单号', '挂号医生', '挂号费', '实付款', '推荐人', '就诊人',
        // '就诊人电话', 
        // '预约时间', '支付方式', '付款状态', '就诊状态'
            $address = $order['address'];
            $dataArray[] = [
                '订单号' => $this->filterValue($order['order_no']),
                '挂号医生' => $this->filterGoodsInfo($order),
                '挂号费' => $this->filterValue($order['total_price']),
            
                '实付款' => $this->filterValue($order['pay_price']),
                '推荐人' => $this->filterValue($order['recommender_name']),
                '就诊人' => $this->filterValue($order['jiuzhen_name']),
                '就诊人电话' => $this->filterValue($order['jiuzhen_phone']),

                '预约时间' => $this->filterValue($order['jiuzhen_day']),

                '支付方式' => $this->filterValue($order['pay_type']['text']),
                
                
                '付款状态' => $this->filterValue($order['pay_status']['text']),
                // '付款时间' => $this->filterTime($order['pay_time']),
                
                '就诊状态' => $this->filterValue($order['order_status']['text']),
                // '微信支付交易号' => $this->filterValue($order['transaction_id']),
            ];
        }
        // 导出csv文件
        $filename = 'order-' . date('YmdHis');
        return export_excel($filename . '.csv', $this->tileArray, $dataArray);
    }
    public function orderList3($list)
    {
        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            /* @var OrderAddressModel $address */
            $address = $order['address'];
            $dataArray[] = [
                '订单号' => $this->filterValue($order['order_no']),
                '商品信息' => $this->filterGoodsInfo($order),
                '订单总额' => $this->filterValue($order['total_price']),
                '优惠券抵扣' => $this->filterValue($order['coupon_money']),
                '积分抵扣' => $this->filterValue($order['points_money']),
                '运费金额' => $this->filterValue($order['express_price']),
                '后台改价' => $this->filterValue("{$order['update_price']['symbol']}{$order['update_price']['value']}"),
                '实付款金额' => $this->filterValue($order['pay_price']),
                '支付方式' => $this->filterValue($order['pay_type']['text']),
                '下单时间' => $this->filterValue($order['create_time']),
                '买家' => $this->filterValue($order['user']['nickName']),
                '买家留言' => $this->filterValue($order['buyer_remark']),
                '配送方式' => $this->filterValue($order['delivery_type']['text']),
                '自提门店名称' => !empty($order['extract_shop']) ? $this->filterValue($order['extract_shop']['shop_name']) : '',
                '自提联系人' => !empty($order['extract']) ? $this->filterValue($order['extract']['linkman']) : '',
                '自提联系电话' => !empty($order['extract']) ? $this->filterValue($order['extract']['phone']) : '',
                '收货人姓名' => $this->filterValue($order['address']['name']),
                '联系电话' => $this->filterValue($order['address']['phone']),
                '收货人地址' => $this->filterValue($address ? $address->getFullAddress() : ''),
                '物流公司' => $this->filterValue($order['express']['express_name']),
                '物流单号' => $this->filterValue($order['express_no']),
                '付款状态' => $this->filterValue($order['pay_status']['text']),
                '付款时间' => $this->filterTime($order['pay_time']),
                '发货状态' => $order['delivery_status']['value'] == 20 ? '已发货' : '未发货',
                '发货时间' => $this->filterTime($order['delivery_time']),
                '收货状态' =>$order['receipt_status']['value'] == 20 ? '已收货' : '未收货',
                '收货时间' => $this->filterTime($order['receipt_time']),
                '订单状态' =>
                    $order['order_status']['value'] == 10 ? '进行中' :
                    ($order['order_status']['value'] == 20 ? '已取消' :
                    ($order['order_status']['value'] == 21 ? '待取消' :
                    ($order['order_status']['value'] == 30 ? '已完成' : '未知')))
                ,
                '微信支付交易号' => $this->filterValue($order['transaction_id']),
                '是否已评价' => $this->filterValue($order['is_comment'] ? '是' : '否'),
            ];
        }
        // 导出csv文件
        $filename = 'order-' . date('YmdHis');
        return export_excel($filename . '.csv', $this->tileArray1, $dataArray);
    }
    /**
     * 批量发货模板
     */
    public function deliveryTpl()
    {
        // 导出csv文件
        $filename = 'delivery-' . date('YmdHis');
        return export_excel($filename . '.csv', ['订单号', '物流单号']);
    }

    /**
     * 格式化商品信息
     * @param $order
     * @return string
     */
    private function filterGoodsInfo($order)
    {
        $content = '';
        foreach ($order['goods'] as $key => $goods) {
            $content .= "{$goods['goods_name']}\n";
            // !empty($goods['goods_attr']) && $content .= "　商品规格：{$goods['goods_attr']}\n";
            // $content .= "　购买数量：{$goods['total_num']}\n";
            // $content .= "　商品总价：{$goods['total_price']}元\n\n";
        }
        return $content;
    }

    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }

    /**
     * 日期值过滤
     * @param $value
     * @return string
     */
    private function filterTime($value)
    {
        if (!$value) return '';
        return $this->filterValue(date('Y-m-d H:i:s', $value));
    }
    /**
    * 患者列表导出
    * @param array $list 导出数据
    * @return mixed
    */
    public function huanzheList($list)
    {
        // 表头
        $headers = [
            '姓名', '性别', '民族', '证件类型', '证件号码','推荐人','推荐微信名称', '出生日期',
            '手机号', '与本人关系', '是否默认', '添加时间'
        ];

        // 表格内容
        $dataArray = [];
        foreach ($list as $item) {
            $dataArray[] = [
                '姓名' => $item['name'] ?? '',
                '性别' => $item['sex'] ?? '',
                '民族' => $item['minzu'] ?? '',
                '证件类型' => $item['zhengjian'] ?? '',
                '证件类型' => $item['zhengjian'] ?? '',
                '证件号码' => $item['zhengjiannb'] ?? '',
                '推荐人' => $item['recommender_name'] ?? '',
                '推荐微信名称' => $item['recommender_nickname'] ?? '',
                '出生日期' => $item['shengri'] ?? '',
                '手机号' => $item['phone'] ?? '',
                '与本人关系' => $item['guanxi'] ?? '',
                '是否默认' => isset($item['is_mr']) ? ($item['is_mr'] == '1' ? '是' : '否') : '',
                '添加时间' => isset($item['create_time']) ? date('Y-m-d H:i:s', $item['create_time']) : '',
            ];
        }

        // 文件名
        $filename = 'huanzhe-' . date('YmdHis');
        return export_excel($filename . '.csv', $headers, $dataArray);
    }
}